package com.company.project.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.company.project.common.utils.DataResult;
import com.company.project.common.utils.Func;
import com.company.project.entity.SysSmscodeEntity;
import com.company.project.entity.SysUser;
import com.company.project.mapper.SysSmscodeMapper;
import com.company.project.service.HttpSessionService;
import com.company.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.company.project.mapper.TZjhmglMapper;
import com.company.project.entity.TZjhmglEntity;
import com.company.project.service.TZjhmglService;

import java.util.Date;
import java.util.List;


@Service("tZjhmglService")
public class TZjhmglServiceImpl extends ServiceImpl<TZjhmglMapper, TZjhmglEntity> implements TZjhmglService {

    @Autowired
    private TZjhmglMapper zjhmglMapper;
    @Autowired
    private SysSmscodeMapper sysSmscodeMapper;
    @Autowired
    private HttpSessionService httpSessionService;
    @Autowired
    private UserService userService;

    @Override
    public DataResult checkYzm(TZjhmglEntity tZjhmgl) {
        try {
            //效验验证码
            TZjhmglEntity tZjhmglEntity = zjhmglMapper.selectById(tZjhmgl.getId());
            String mobile = tZjhmglEntity.getZjhm();
            String smscode = tZjhmglEntity.getYzm();
            //效验验证码
            SysSmscodeEntity sysSmscode = sysSmscodeMapper.selectOne(Wrappers.<SysSmscodeEntity>lambdaQuery()
                    .eq(SysSmscodeEntity::getPhone, mobile)
                    .eq(SysSmscodeEntity::getSmscode, smscode)
            );
            if (Func.isNull(sysSmscode)) {
                return DataResult.fail("验证码错误");
            }

            Date time = sysSmscode.getTime();
            Date date = new Date();
            // 计算时间差（毫秒）
            long timeDifference = date.getTime() - time.getTime();
            long l = timeDifference / 1000/60;
            if (l > 5) {
                return DataResult.fail("验证码超时,5分钟内有效");
            }
        }catch (Exception e){
            e.printStackTrace();
            return DataResult.fail("验证码效验失败，请联系管理员");
        }
        return DataResult.success();
    }

    @Override
    public Object setCaller(String id) {
        //获取当前操作人
        //通过access_token拿userId
        String userId = httpSessionService.getCurrentUserId();
        SysUser sysUser = userService.getById(userId);
        zjhmglMapper.updateZjhm(sysUser.getUsername());//全部设置未使用

        TZjhmglEntity tZjhmgl = new TZjhmglEntity();
        tZjhmgl.setId(id);
        tZjhmgl.setStart("1");//设置为使用中
        this.updateById(tZjhmgl);
        return null;
    }


}